package com.example.springboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String authorizationHeader = request.getHeader("Authorization");
        System.out.println("Authorization Header: " + authorizationHeader); // 调试日志

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            System.out.println("Extracted Token: " + token); // 调试日志

            if (jwtTokenUtil.validateToken(token)) {
                // Token 验证成功，提取用户信息
                String username = jwtTokenUtil.getUsernameFromToken(token);
                String realUserId = jwtTokenUtil.getRealUserIdFromToken(token); // 新增解析 realUserId
                String role = jwtTokenUtil.getRoleFromToken(token);

                // 设置在请求属性中，供后续使用
                request.setAttribute("username", username);
                request.setAttribute("realUserId", realUserId); // 新增 realUserId
                request.setAttribute("role", role);
                System.out.println("Validated - Username: " + username + ", RealUserId: " + realUserId + ", Role: " + role); // 调试日志
            } else {
                System.out.println("Token validation failed");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("无效的 Token");
                return;
            }
        } else {
            System.out.println("No valid Authorization header found");
        }
        filterChain.doFilter(request, response);
    }
}